﻿using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace System.Xml
{
    public class XmlHelper
    {
        public static T Deserialize<T>(string str) where T : class, new()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            StringReader sr = new StringReader(str);
            return (T)serializer.Deserialize(sr);
        }

        public static XmlDocument Load(string fileName)
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(fileName);
            return xmlDocument;
        }

        public static XmlDocument LoadXml(string xmlString)
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(xmlString);
            return xmlDocument;
        }
        public static string XmlDocumentToString(XmlDocument doc)
        {

            MemoryStream stream = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(stream, null);
            writer.Formatting = Formatting.Indented;
            doc.Save(writer);

            StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8);
            stream.Position = 0;
            string xmlString = sr.ReadToEnd();
            sr.Close();
            stream.Close();

            return xmlString;
        }
        public static void SaveAs(string xmlStr, string path)
        {
            if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path");
        }

        public static string Serialize(object o)
        {
            var settings = new XmlWriterSettings();
            // 2023/3/9 mes调试添加 true    去除顶部xml声明
            settings.OmitXmlDeclaration = false;
            // mes 使用utf8
            settings.Encoding = Encoding.UTF8;
            // 换行
            settings.Indent = true;

            var ms = new MemoryStream();
            using (XmlWriter sw = XmlWriter.Create(ms, settings))
            {
                // 2023/3/9 mes调试添加 去除顶部命名空间
                var ns = new XmlSerializerNamespaces();
                ns.Add("", "");
                XmlSerializer serializer = new XmlSerializer(o.GetType());
                serializer.Serialize(sw, o, ns);
            }

            var res = Encoding.UTF8.GetString(ms.ToArray());
            if (res[0] != '<')
                res = res.Substring(1);
            return res;
        }


        /// <summary>获取TibcoMessage 的MessageName</summary>
        public static string GetMessageName(string xml)
            => GetXPathText(xml, "//MESSAGENAME");

        /// <summary>获取ReplySubject</summary>
        public static string GetReplySubject(string xml)
            => GetXPathText(xml, "//REPLYSUBJECTNAME");

        /// <summary>获取时间戳</summary>
        public static string GetTransactionId(string xml)
            => GetXPathText(xml, "//TRANSACTIONID");


        private static string GetXPathText(string xml, string xpath)
        {
            string res = "";

            try
            {
                var doc = LoadXml(xml);
                XmlNodeList nodes = doc.SelectNodes(xpath);

                if (nodes == null || nodes.Count == 0) return res;
                res = nodes[0].InnerText;
                return res;
            }
            catch (Exception)
            {
                return res;
            }

        }

        public static string SetReplyMessageName(string xml)
        {
            var doc = LoadXml(xml);
            XmlNodeList nodes = doc.SelectNodes("//MESSAGENAME");

            if (nodes != null && nodes.Count == 1)
            {
                nodes[0].InnerText = nodes[0].InnerText.Replace("Request", "Reply");
            }

            return XmlDocumentToString(doc);
        }

        public static string SetJobReply(string xml)
        {
            var doc = LoadXml(xml);
            XmlNodeList nodes = doc.SelectNodes("//MESSAGENAME");

            if (nodes != null && nodes.Count == 1)
            {
                nodes[0].InnerText = "PalletRequestTransportJobReply";
            }

            return XmlDocumentToString(doc);
        }

        public static string SetXmlNodeText(string xml, string nodeName, string text)
        {
            var doc = LoadXml(xml);
            XmlNodeList nodes = doc.SelectNodes($"//{nodeName.ToUpper()}");

            if (nodes != null && nodes.Count == 1)
            {
                nodes[0].InnerText = text;
            }

            return XmlDocumentToString(doc);
        }

        public static string SetNGReturn(string xml, string code, string message = "")
        {
            var doc = LoadXml(xml);
            XmlNodeList nodes = doc.SelectNodes("//RETURNCODE");

            if (nodes != null && nodes.Count == 1)
            {
                nodes[0].InnerText = code;
            }

            XmlNodeList nodes1 = doc.SelectNodes("//RETURNMESSAGE");

            if (nodes1 != null && nodes1.Count == 1)
            {
                nodes1[0].InnerText = message;
            }

            return XmlDocumentToString(doc);
        }


       
    }
}